import React, { useState, useRef, useEffect } from 'react';
import {  } from 'antd-mobile';
import {  
  AppOutline,
  MessageOutline,
  MessageFill,
  UnorderedListOutline,
  UserOutline,
} from 'antd-mobile-icons';
import Poem from '../Poem';
import { useDispatch, useMappedState } from 'redux-react-hook';
import { actionChangeRoom, actionSay, actionShowArticleProcess, actionLove } from '../../action';
import './style.less';
import { checkStatus, rpx, typeTimer } from '../../utils';
import { GET_ARTICLE } from '../../constant';


export default function ChatRoom() {
  const dispatch = useDispatch();
  const mapState = React.useCallback((state) => {
    return {
      state,
      uiStore: state.uiStore,
      poem: state.poem,
    };
  }, []);
  const { state, uiStore, poem } = useMappedState(mapState);
  const stateRef = useRef(state);
  stateRef.current = state;
  const [ chatState, setChatState ] = useState({
    sayIng: false, // 当前是否在说话
  });
  const chatStateRef = useRef(chatState);
  chatStateRef.current = chatState;

  const handleChangeRoom = () => {
    actionChangeRoom({}, state, dispatch);
  }

  // 聊天窗等待第一句话的进入，你 亦或是 我
  useEffect(() => {
    window.addEventListener('weSay', (e) => {
      const itemData = e.detail.data;
      actionSay({}, stateRef.current, dispatch);
      nextSay();
      let chatDom = document.querySelector('#chat-main');
      let chatContentDom = document.querySelector('#chat-content-wrap');
      if (chatDom) {
        chatDom.scrollTop = chatContentDom.offsetHeight;
      }
    });
  }, []);

  // 我们要说下一句话
  const nextSay = () => {
    let nextChatIndex = stateRef.current.store.chatIndex + 1;
    let nextPoem = stateRef.current.poem[ nextChatIndex ];
    if ( nextPoem ) {
      let typeTime = typeTimer( nextPoem );
      setTimeout(() => {
        window.dispatchEvent(
          new CustomEvent('weSay', {
            bubbles: true,
            detail: {
               data: {},
            },
          }),
        );
      }, typeTime);
      if ( 
        nextPoem.type === 'ahkari' 
      )  {
        setTimeout(() => {
          setChatState({ ...chatStateRef.current,
            sayIng: true,
          });
        }, typeTime * ( 0.2 ) );
        setTimeout(() => {
          setChatState({ ...chatStateRef.current,
            sayIng: false,
          });
        }, typeTime * 1 );
      }
      
    } else {
      let cPoem = stateRef.current.poem[ stateRef.current.store.chatIndex ];
      if ( !cPoem ) {
        // 留着解一辈子的bug，为何这个地方爱总是会溢出多一点点？？？
        if ( checkStatus(stateRef.current) ) {
          // 溢出之时，也是表白之时
          actionLove({}, stateRef.current, dispatch);
          setTimeout(() => {
            window.dispatchEvent(
              new CustomEvent('weSay', {
                bubbles: true,
                detail: {
                  data: {},
                },
              }),
            );
          }, 500);
        }
        return;
      }

      if ( cPoem.sayType === 'article' ) {
        return; // article弹出则停止
      }

      // 话讲完了，得弹出 article 了！！！
      actionShowArticleProcess({}, stateRef.current, dispatch);
      setTimeout(() => {
        window.dispatchEvent(
          new CustomEvent('weSay', {
            bubbles: true,
            detail: {
               data: {},
            },
          }),
        );
      }, 500);
    }
  }

  return (
    <div className="chat-room-container"
      style={{
        left: uiStore.status === 'home' ? rpx(750) : rpx(0),
        background: 'red'
      }}
    >
      <div className="chat-top" style={{
        height: rpx(95),
      }}>
        <img 
          className="chat-top-img"
          src="https://gw.alicdn.com/imgextra/i4/O1CN01czRR7k1CmNRmIh9lB_!!6000000000123-0-tps-1125-142.jpg" 
          alt=""
        />
        <div className="chat-top-left-icon" style={{
          // background: 'red',
          left: 0,
          top: 0,
          height: rpx(95),
          width: rpx(120),
        }} onClick={() => {
          handleChangeRoom();
        }}>

        </div>
        <div className="chat-title-text">
          {
            chatState.sayIng ? '对方正在输入...' : '郭启织'
          }
        </div>
      </div>
      <div className="chat-main" id="chat-main" style={{
        top: rpx(95),
        bottom: rpx(186),
      }}>
        <div className="chat-content-wrap" id="chat-content-wrap" style={{
          // transform: `translate(0px, ${170}px)`
        }}>
          {
            (
              poem.slice(0, state.store.chatIndex + 1)
            ).map((p, i) => {
              return <Poem 
                key={i}
                content={p}
              />;
            })
          }
        </div>
      </div>
      <div className="chat-bottom" style={{
        height: rpx(186),
      }}>
        <img 
          className="chat-bottom-img"
          src="https://gw.alicdn.com/imgextra/i4/O1CN01Tid98U1DVGGH1ysIQ_!!6000000000221-0-tps-1125-279.jpg" 
          alt=""
        />
      </div>
      
    
    </div>
  );
}
